package io.bdmc.modules.sys.controller;

import java.time.LocalDateTime;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.bdmc.common.annotation.SysLogger;
import io.bdmc.common.utils.MyMap;
import io.bdmc.common.utils.MyPage;
import io.bdmc.common.utils.R;
import io.bdmc.common.validator.Assert;
import io.bdmc.common.validator.ValidatorUtils;
import io.bdmc.common.validator.group.AddGroup;
import io.bdmc.common.validator.group.UpdateGroup;
import io.bdmc.modules.bss.entity.SmkPush;
import io.bdmc.modules.bss.service.ISmkPushService;
import io.bdmc.modules.sys.entity.SysUser;
import io.bdmc.modules.sys.service.SysUserService;

/**
 * 系统用户
 * 
 * @author huang lu
 * @email hlkyo@qq.com
 * @date 2016年10月31日 上午10:40:10
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private ISmkPushService pushSvs;
	
	/**
	 * 所有用户列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(@RequestParam Map<String, String> params){
		//查询列表数据
		Long current =Long.valueOf(params.get("current"));
		Long size = Long.valueOf(params.get("size"));
		String username = params.get("username");
		MyPage<SysUser> myPage = new MyPage<SysUser>(current,size);
        MyPage<SysUser> map = sysUserService.queryList(myPage,username);
		return R.ok().putData(MyMap.ok(map.getRecords(), map.getTotal()));
	}
	
	/**
	 * 获取登录的用户信息
	 */
	@RequestMapping("/info")
	public R info(){
		return R.ok().put("data", getUser());
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLogger("修改密码")
	@RequestMapping("/password")
	public R password(@RequestBody Map<String, String> params){
		String password = params.get("password");
		String newPassword = params.get("newPassword");

		Assert.isBlank(newPassword, "新密码不为能空");

		//sha256加密
		password = new Sha256Hash(password, getUser().getSalt()).toHex();
		//sha256加密
		newPassword = new Sha256Hash(newPassword, getUser().getSalt()).toHex();
				
		//更新密码
		SysUser user = sysUserService.getById(getUserId());
		user.setPassword(newPassword);
		boolean count = user.updateById();
		//boolean count = sysUserService.updatePassword(getUserId(), password, newPassword);
		if(!count){
			return R.error("原密码不正确");
		}
		return R.trueOfFalse(count);
	}

	/**
	 * 重置用户密码
	 */
	@SysLogger("重置密码")
	@RequestMapping("/resetpwd")
	public R resetPwd(Long id){
		SysUser user = sysUserService.getById(id);
		if(user==null)
		return R.error("参数错误。");
		//sha256加密
		String newPassword = new Sha256Hash("123456", user.getSalt()).toHex();	
		//更新密码
		user.setPassword(newPassword);
		boolean count = user.updateById();
		//boolean count = sysUserService.resetPassword(user.getUserId(),newPassword);
		return R.trueOfFalse(count);
	}
	
	/**
	 * 用户信息
	 */
	@RequestMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId){
		SysUser user = sysUserService.QueryObject(userId);
		return R.ok().put("data", user);
	}
	
	/**
	 * 保存用户
	 */
	@SysLogger("保存用户")
	@RequestMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody SysUser user){
		ValidatorUtils.validateEntity(user, AddGroup.class);
		user.setCreateBy(getUser().getUsername());
		user.setCreateTime(LocalDateTime.now());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		Boolean r = sysUserService.save(user);

		if(r&&user.getConfigId()!=null&&user.getConfigId()>0){
			SmkPush p = new SmkPush();
			p.setUserId(user.getUserId());
			p.setConfigId(user.getConfigId());
			p.setCreateBy(getUser().getUsername());
			p.setCreateDate(LocalDateTime.now());
			p.insert();
		}
		
		return R.ok();
	}
	
	/**
	 * 修改用户
	 */
	@SysLogger("修改用户")
	@RequestMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R update(@RequestBody SysUser user){
		ValidatorUtils.validateEntity(user, UpdateGroup.class);
		sysUserService.updateById(user);
		QueryWrapper<SmkPush> w1 = new QueryWrapper<>();
		w1.eq("user_id", user.getUserId());
		SmkPush p1 = pushSvs.getOne(w1);
		if(p1!=null&&user.getConfigId()!=null&&user.getConfigId()>0){
			p1.setConfigId(user.getConfigId());
			p1.updateById();
		}
		return R.ok();
	}
	
	/**
	 * 删除用户
	 */
	@SysLogger("删除用户")
	@RequestMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long userId){
		if(userId==1L){
			return R.error("系统管理员不能删除");
		}
		
		if(userId==getUserId()){
			return R.error("当前用户不能删除");
		}
		
		sysUserService.removeById(userId);
		return R.ok();
	}
}
